package com.wzy.gulimall.product.exception;

import com.wzy.common.exception.BizCodeEnume;
import com.wzy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * 描述
 * 创建人    Wzy
 * 创建时间: 2020-05-11  1:04
 */
@RestControllerAdvice
@Slf4j
public class GulimallExeceptionControllerAdvide {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        log.error("数据校验出现错误{},异常类型{}", e.getMessage(), e.getClass());
        HashMap<String, String> map = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().stream().forEach((item) -> {
            map.put(item.getField(), item.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(), BizCodeEnume.VALID_EXCEPTION.getMsg()).put("date", map);
    }

    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable throwable) {
        System.out.println(throwable.getMessage());
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
